import Taro, { Component } from '@tarojs/taro'
import {View, Text, Image} from '@tarojs/components'

import { connect } from '@tarojs/redux'
import { jumpUrl } from '../../utils/router'
import {asyncUserMoney} from '../../actions/user'
import {orderRefresh} from '../../actions/order'
import { getEnvelope } from '../../api/user'
import './minute.styl'
import btnPng from '../../assets/images/game/btn.png'

let Timeout = null
@connect(({ user }) => ({
  user
}), (dispatch) => ({
  
  // 加载用户余额
  onAsyncUserMoney () {
    dispatch(asyncUserMoney())
    
  },
  // 设置需要刷新订单列表
  onOrderRefresh () {
    dispatch(orderRefresh(true))
  },

 
}))
class Minute extends Component {
  constructor () {
    super(...arguments)
    this.state = {
      start: false, // 是否开始
      startTime: Date.now(), // 开始时间
      count: 0, // 耗时计数
      result: false, // 展示结果
      coupon: null,
      voucher: null, // 
      envelop: null
    }
    Taro.removeStorageSync('no_gift');
    
  }
  config = {
    navigationBarTitleText: '拍十秒'
  }
  // 下拉刷新
  onPullDownRefresh () {
    Taro.stopPullDownRefresh()
  }

  onGetUserInfo (data) {
    console.log(data)
  }

  handleOrderClick (value) {
    console.log(value)
  }
  // 跳转
  jumpTo (url) {
    jumpUrl(url, {method: 'navigateTo'})
  }

  // 开始游戏 、 结束游戏
  startGame () {
    var noPlay = Taro.getStorageSync('no_gift');
    if(noPlay=='1') return false;
    Taro.vibrateShort({})
    if (!this.state.start) {
      this.setState({
        start: true, // 开始
        startTime: Date.now(), // 开始时间
        count: 0
      })
      this.setTimeout()
    } else {
      clearTimeout(Timeout)
      const nowTime =  Date.now()
      const count = nowTime - this.state.startTime
      this.setState({
        start: false, // 开始
        count
      })
      this.endGame()
    }

  }

  // 结束游戏并查询中奖结果
  endGame () {
    const {token} = this.props.user
    this.props.onOrderRefresh() // 完成游戏通知订单列表刷新
    const {
      type, // 1每日签到拍十秒  2订单完成奖励拍十秒机会
      shop_id, // 签到的时候传当前店铺 订单的传订单归属店铺
      order_code // 订单编号
    } = this.$router.params // 通过路由传递进来拍十秒的信息
    const now = new Date()
    const date = `${now.getFullYear()}${('0' + (now.getMonth() + 1)).slice(-2)}${('0' + now.getDate()).slice(-2)}`
    setTimeout(() => {
      const {count} = this.state
      getEnvelope({token, type, shop_id, order_code, date, second: count / 1000}).then(({data, status, msg}) => {       

        if (!status) {
          
          // 不能在玩了
          Taro.setStorageSync('no_gift', '1');
          Taro.showToast({
            title: '抱歉没有中奖',
            icon: 'none',
            duration: 2000,
            complete:function(){
              setTimeout(function () {
              Taro.navigateBack();
              },2000)
            }
          })
          return
        }
        if (data.result === 0) {
          // 不能在玩了
          Taro.setStorageSync('no_gift', '1');
          Taro.showToast({
            title: msg,
            icon: 'none',
            duration: 2000,
            complete:function(){
              setTimeout(function () {
              Taro.navigateBack();
              },2000)
            }
          })
          return
        }
        if (data.voucher || data.envelop) {
          // 不能在玩了
          Taro.setStorageSync('no_gift', '1');
          this.setState({
            result: true,
            voucher: data.voucher,
            envelop: data.envelop,
          })
        }
        
      })
    }, 100)
  }


  // 随机时间更新state
  setTimeout () {
    Timeout = setTimeout(() => {
      const nowTime =  Date.now()
      const count = nowTime - this.state.startTime
      this.setState({
        count
      })
      // 如果超过 15秒 清空
      if (count > 15 * 1000) {
        this.setState({
          start: false // 结束
        })
      } else {
        this.setTimeout()
      }
    }, Math.floor(Math.random() * 100))
  }

  // 关闭
  close () {
    Taro.showToast({
      title: '领取成功',
      icon: 'none'
    })
    setTimeout(() => {
      Taro.navigateBack({ delta: 1 })
    }, 1000)
  }

  componentWillReceiveProps (nextProps) {
    console.log(this.props, nextProps)
  }
  componentDidMount () { }
  componentWillUnmount () { }

  componentDidShow () {
    this.setState({
      start: false, // 是否开始
      startTime: Date.now(), // 开始时间
      count: 0 // 耗时计数
    })
  }

  componentDidHide () {
    clearTimeout(Timeout)
  }

  render () {
    const {count, result, coupon, envelop,voucher} = this.state
    return (
      <View className='game-minutes'>
        <View className='minutes'>
          <View className='inner'>
            {parseFloat(count / 1000).toFixed(3)}
          </View>
        </View>
        <Image src={btnPng} className='btn' onClick={this.startGame.bind(this)} />
        <View className='guize'>
        规则说明：
        <View className='game-tips'>1 . 每天及确认收货后可拍一次 ，随机派发红包和券 ，越接近10秒中奖概率越高 。</View>
        <View className='game-tips'>2 . 代金券线上线下通用 ，门店消费可通过门店优惠买单按钮使用 。</View>
        </View>

        {/*结果*/}
        {result && <View className='cloud'>
          <View className='bag'>
            {coupon && <View className='card coupon'>
              <Text className='amount'>{coupon.coupon_name}</Text>
            </View>}
            {voucher && <View className='card coupon'>
              <Text className='amount'>{voucher.voucher_name}</Text>
            </View>}
            {envelop && <View className='card envelop'>
              <Text className='symbol'>RMB</Text>
              <Text className='amount'>{(envelop.money / 100).toFixed(2)}</Text>
              <Text className='symbol'>元</Text>
            </View>}
            <View className='submit' onClick={this.close.bind(this)} />
            {/*<View className='cancel' />*/}
          </View>
        </View>}

      </View>
    )
  }
}

export default Minute
